<?php

namespace app\admin\controller;

use app\common\controller\BasicAdmin;
use app\common\traits\SelectPage;
use app\common\model\UserModel;
use app\common\model\MessageModel;
use think\Exception;

/**
 * Class SchoolMessage
 */
class Message extends BasicAdmin
{
    use SelectPage;

    /**
     * 通知管理
     */
    protected $model = 'MessageModel';

    public function index(){
        $this->title = '通知管理';
        return  $this->_query($this->model)
            ->with(['user'])
            ->like('name')
            ->page();
    }

    /**
     * 添加
     */
    public function add()
    {
        // 发送订阅消息
        if($this->request->isPost())
        {
            $uids = $this->request->post('read_uid');
            $uids = explode(',', $uids);
            foreach ($uids as $uid)
            {
                $saveData = [
                    'title' =>  $this->request->post('title'),
                    'desc' =>  $this->request->post('desc'),
                    'read_uid' =>  $uid,
                ];
                MessageModel::create($saveData);

                $user = UserModel::find($uid);
                $data = [
                    "touser"=> $user['openid'],
                    "template_id"=> config('wechat.miniapp.jiaoshi_tpl'),
                    "page"=> "pages/user/user",
                    "data"=> [
                        "thing1"=> [
                            "value"=> $this->request->post('title')
                        ],
                        "thing6"=> [
                            "value"=> $this->request->post('desc')
                        ],
                        "date3"=> [
                            "value"=> date('Y-m-d H:i')
                        ],
                    ]
                ];
                try {
                    $ret = \We::WeMiniTemplate(config('wechat.miniapp'))->send($data);
                }catch (\Exception $e){
                    continue;
                }
            }
            return ["code"=>1,"info"=>"恭喜, 数据保存成功!","data"=>""];
        }
        $this->title = '添加';
        return $this->_form($this->model, 'form');
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $this->title = '编辑';
        return $this->_form($this->model, 'form');
    }

    /**
     * 删除
     */
    public function del()
    {
        $this->_delete($this->model);
    }

    /**
     * 启用/关闭
     */
    public function upstatus(){
        $this->_save($this->model, [
            'status' => $this->request->request('status'),
        ],'id', ['id' => $this->request->request('id')]);
    }


}